package com.wgz.medicalmanagement.controller;

import com.wgz.medicalmanagement.common.entity.Result;
import com.wgz.medicalmanagement.service.ChatHistoryService;
import com.wgz.medicalmanagement.service.impl.AIDiagnosisServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * AI诊断控制器
 * 处理与AI诊断相关的请求
 *
 * @author medical
 */
@Slf4j
@RestController
@RequestMapping("/api/ai-diagnosis")
@RequiredArgsConstructor
public class AIDiagnosisController {

    private final AIDiagnosisServiceImpl aiDiagnosisService;
    private final ChatHistoryService chatHistoryService;

    /**
     * 发送消息到AI并获取回复
     *
     * @param requestBody 请求体，包含消息内容
     * @return AI回复内容
     */
    @PostMapping("/chat")
    public ResponseEntity<Result<Map<String, Object>>> chatWithAI(@RequestBody Map<String, Object> requestBody) {
        String message = (String) requestBody.get("message");
        
        // 必须从请求中获取有效的用户ID
        if (requestBody.get("userId") == null) {
            return ResponseEntity.badRequest().body(Result.fail("用户ID不能为空"));
        }
        
        Long userId = Long.parseLong(requestBody.get("userId").toString());
        String sessionId = (String) requestBody.get("sessionId");
        
        if (message == null || message.trim().isEmpty()) {
            return ResponseEntity.badRequest().body(Result.fail("消息不能为空"));
        }
        
        // 如果没有提供会话ID，创建新的会话
        if (sessionId == null || sessionId.trim().isEmpty()) {
            sessionId = chatHistoryService.generateSessionId();
        }
        
        log.info("收到AI诊断请求: userId={}, sessionId={}, message={}", userId, sessionId, message);
        
        try {
            // 保存用户消息
            chatHistoryService.saveUserMessage(userId, sessionId, message);
            
            // 调用带用户ID的AI服务
            String aiResponse = aiDiagnosisService.chatWithAI(userId, message);
            
            // 保存AI响应
            chatHistoryService.saveAiMessage(userId, sessionId, aiResponse);
            
            Map<String, Object> response = new HashMap<>();
            response.put("reply", aiResponse);
            response.put("timestamp", System.currentTimeMillis());
            response.put("sessionId", sessionId);
            
            return ResponseEntity.ok(Result.success("AI响应成功", response));
        } catch (Exception e) {
            log.error("AI诊断请求处理失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body(Result.fail("AI诊断请求处理失败: " + e.getMessage()));
        }
    }
    
    /**
     * 导出诊断报告
     *
     * @param patientId 患者ID
     * @return 诊断报告URL
     */
    @GetMapping("/export-report/{patientId}")
    public ResponseEntity<Result<String>> exportDiagnosisReport(@PathVariable Long patientId) {
        log.info("导出患者 {} 的诊断报告", patientId);
        
        try {
            // 调用真实服务生成报告
            String reportUrl = aiDiagnosisService.exportDiagnosisReport(patientId);
            return ResponseEntity.ok(Result.success("报告生成成功", reportUrl));
        } catch (Exception e) {
            log.error("诊断报告生成失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body(Result.fail("诊断报告生成失败: " + e.getMessage()));
        }
    }
} 